<?php

class SubmissionsModule extends Module {
	const PER_PAGE = 100;
	
	public function index() {
		redirect(WEB_ROOT . '/tasks/');
	}
	
	public function result($para) {
		requireUser();
		
		$model = new SubmissionModel();
		
		$page = intval(isset($para[0]) ? $para[0] : 1);
		$page = min($page, 1);
		
		$pager = new Pager($page, self::PER_PAGE, $model->getNumRecords());
		$this->set('pager', $pager);
		$this->set('data', $model->getRecordRange($pager->firstRecord, self::PER_PAGE));
		$this->render('submission');
	}
	
	public function submit() {
		requireUser();
		$this->render('submit');
	}
	
	public function confirm() {
		requireUser();
		
		$file     = $_FILES['a'];
		$tmp_name = $file ['tmp_name'];
        $name     = $file ['name'];
        $error    = $file['error'];
        $size     = $file['size'];
        
        if ($error != 0 || $size > 204800) {
        	if ( $size > 204800) {
        		$error = UPLOAD_ERR_INI_SIZE;
        	}
        	
        	switch ($error) {
        		case UPLOAD_ERR_FORM_SIZE:
        		case UPLOAD_ERR_INI_SIZE:
        			$this->set('submit_error', 4);
					$this->render('submit');
					return;
        		case UPLOAD_ERR_PARTIAL:
        		case UPLOAD_ERR_NO_FILE:
        			$this->set('submit_error', 3);
					$this->render('submit');
					return;
        		default:
        			$this->set('submit_error', 5);
					$this->render('submit');
					return;
        	}
        }
        
        $lang = '';
        $task = '';
        
        $file_c   = file($tmp_name);
        foreach ($file_c as $line) {
        	$l = explode(':', trim($line), 2);
        	if (count($l) > 1) {
        		$l[0] = strtoupper(trim($l[0]));
        		if ($l[0] == 'LANG') $lang = trim($l[1]);
        		if ($l[0] == 'TASK') $task = trim($l[1]);
        	}
        }
        
        $lang = strtolower($lang);
        if ($lang == 'c++') $lang = 'cpp';
        
        if (empty($lang) || !($lang == 'c' || $lang == 'cpp')) {
        	$this->set('submit_error', 2);
			$this->render('submit');
			return;
        }
        
        $task = strtolower($task);
        
        $taskModel = new TaskModel();
        
        if (empty($task) || !$taskModel->taskExist($task)) {
        	$this->set('submit_error', 1);
			$this->render('submit');
			return;
        }
        
        $s = new SubmissionObject();
        $s->status = 1;
        
        $s->time = time();
        $s->uid = Auth::getAuth()->id;
        $s->task = $task;
        $s->lang = strtolower($lang);
        
        $id = $s->insert();
        move_uploaded_file($tmp_name, SUBMIT . '/' . $id . '.source');
        
        $s->status = 0;
        $s->update();
        
        // Update score -5*num
        $user = new UserDataObject($s->uid);
		$user->num_submit++;
		$user->score -= 5*$user->num_submit;
		$user->update();
		
		redirect(WEB_ROOT . '/submissions/result');
	}
}
